package com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study4.controller;

import com.alibaba.fastjson2.JSON;
import com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study4.entity.Weather;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RestController
@RequestMapping("/resttemplate")
@Slf4j
public class TianXingApiRestTemplateController {
    @Autowired
    private RestTemplate restTemplate;   // 可以设置连接超时，读取超时
    /**
     * 使用  resttemplate get和post请求第三方天行api     GET请求中的getForObject 和 getForEntity 方法不支持传递头信息，
     * 需要使用 通用方法exchange
     * @return
     */
    @GetMapping("/test")
    public Object test1(@RequestParam Map<String, String> map) throws Exception {
        String RequestData = "";  // 结果
        // 方式一   直接拼接参数
//        String url = "https://apis.tianapi.com/tianqi/index?key=4556c57375b2fcda12f6fc50f8570558&city=北京&type=1";
//        Weather forObject = restTemplate.getForObject(url, Weather.class);
//        RequestData = JSON.toJSONString(forObject);
        // 方式二  使用占位符 1    请求路径还可以为：name={0}&age={1}
//        String url = "https://apis.tianapi.com/tianqi/index?key={key}&city={city}&type={type}";
//        Weather weather = restTemplate.getForObject(url, Weather.class, "4556c57375b2fcda12f6fc50f8570558", "上海", 1);
//        RequestData= JSON.toJSONString(weather);
        // 方式二  使用占位符 2  通过 Map 传递参数，此种方式必须使用占位符，并且 map 中的 key 值，要与请求路径中的 占位符一致
        String url = "https://apis.tianapi.com/tianqi/index?key={key}&city={city}&type={type}";
        Map<String, Object> map1 = new HashMap<>();
        map1.put("key", "4556c57375b2fcda12f6fc50f8570558");
        map1.put("city", "郑州");
        map1.put("type", "1");

        Weather weather = restTemplate.getForObject(url, Weather.class, map1);
        RequestData= JSON.toJSONString(weather);
        return RequestData;
    }
    @GetMapping("/test2")   // 设置请求头
    public Object test2(@RequestParam Map<String, String> map) throws Exception {
        String RequestData = "";  // 结果
        String url = "https://apis.tianapi.com/tianqi/index?key={key}&city={city}&type={type}";
        // 定义头信息
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/x-www-form-urlencoded");
        headers.add("Connection","keep-alive");
        // 请求参数
        Map<String,Object> map1 = new HashMap<>();
        map1.put("key", "4556c57375b2fcda12f6fc50f8570558");
        map1.put("city", "北京");
        map1.put("type", "1");
        // 使用httpEntity 对头信息进行封装
        HttpEntity<Map<String,Object>> entity = new HttpEntity<>(headers);
        // 请求方法  exchange
        ResponseEntity<Weather> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Weather.class, map1);
        Weather body = responseEntity.getBody();
        RequestData = JSON.toJSONString(body);
        return RequestData;
    }
    @GetMapping("/test3")
    public Object test3(@RequestParam Map<String, String> map) throws Exception {
        String RequestData = "";  // 结果
        return RequestData;
    }
    // post方式  注意  带有 @RequestBody 注解的请求  此种情况下，请求参数可以为 设置User 对象，也可以说使用Map
    // 不带@RequestBody 注解的请求  此种情况下，传的参数需要使用MultiValueMap   适用于表单类型提交
    @PostMapping("/test4")
    public Object test4(@RequestBody Map<String, String> map) throws Exception {
        String responseData = "";
        String url = "https://apis.tianapi.com/tianqi/index";
        // 定义头信息
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/x-www-form-urlencoded");
        headers.add("Connection","keep-alive");
        /**
         * 注意  带有 @RequestBody 注解的请求  此种情况下，请求参数可以为 设置User 对象，也可以说使用Map
         *  不带@RequestBody 注解的请求  此种情况下，传的参数需要使用MultiValueMap
         */
        MultiValueMap<String, Object> map1 = new LinkedMultiValueMap<>();
        map1.add("key", "4556c57375b2fcda12f6fc50f8570558");
        map1.add("city", "郑州");
        map1.add("type", "1");
        // 使用httpentity把请求头对象user 和header 进行组装
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map1, headers);
        Weather weather = restTemplate.postForObject(url,httpEntity, Weather.class);
        responseData = JSON.toJSONString(weather);
        return responseData;
    }

    // post方式  exchange方式   如果contenttype是application/json;charset=utf-8格式，参数设置可以使用对象，map
    // 如果contenttype是application/x-www-form-urlencoded格式，参数设置使用MultiValueMap添加，请求头信息格式不变
    @PostMapping("/test5")
    public Object test5(@RequestBody Map<String, String> map) throws Exception {
        String responseData = "";
        String url = "https://apis.tianapi.com/tianqi/index";
        // 定义头信息
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/x-www-form-urlencoded");
        headers.add("Connection","keep-alive");
        /**
         * 注意  带有 @RequestBody 注解的请求  此种情况下，请求参数可以为 设置User 对象，也可以说使用Map
         *  不带@RequestBody 注解的请求  此种情况下，传的参数需要使用MultiValueMap
         */
        MultiValueMap<String, Object> map1 = new LinkedMultiValueMap<>();
        map1.add("key", "4556c57375b2fcda12f6fc50f8570558");
        map1.add("city", "平顶山");
        map1.add("type", "1");
        // 使用httpentity把请求头对象user 和header 进行组装
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map1, headers);
        ResponseEntity<Weather> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Weather.class);
        Weather weather = responseEntity.getBody();
        responseData = JSON.toJSONString(weather);
        return responseData;
    }

    /**
     * post方式之，json数据格式
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/test6")
    public Object test6(@RequestBody Map<String, String> map) throws Exception {
        String responseData = "";
        String url = "http://localhost:8080/resttemplate/testjson";
        // 定义头信息
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json;charset=utf-8");
        headers.add("Connection","keep-alive");
        /**
         * 注意  带有 @RequestBody 注解的请求  此种情况下，请求参数可以为 设置User 对象，也可以说使用Map
         *  不带@RequestBody 注解的请求  此种情况下，传的参数需要使用MultiValueMap
         */
        // 如果请求带有@RequestBody的参数类型，使用对象，map集合设置入参     不带的话，使用 MultiValueMap
        Map<String, Object> map1 = new HashMap<>();
        map1.put("key", "4556c57375b2fcda12f6fc50f8570558");
        map1.put("city", "平顶山");
        map1.put("type", "1");
        // 使用httpentity把请求头对象user 和header 进行组装
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map1, headers);
        ResponseEntity<Weather> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Weather.class);
        Weather weather = responseEntity.getBody();
        responseData = JSON.toJSONString(weather);
        return responseData;
    }
    /**
     * post方式之，json数据格式
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/test7")
    public Object test7(@RequestBody Map<String, String> map) throws Exception {
        String responseData = "";
        String url = "http://localhost:8080/resttemplate/testjson1";
        // 定义头信息
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json;charset=utf-8");
        headers.add("Connection","keep-alive");
        String params = "{\"code\": 1,\"msg\": \"1\",\"result\": null}";
        // 使用httpentity把请求头对象user 和header 进行组装
        HttpEntity<Object> httpEntity = new HttpEntity<>(params, headers);
        ResponseEntity<Weather> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Weather.class);
        Weather weather = responseEntity.getBody();
        responseData = JSON.toJSONString(weather);
        return responseData;
    }

    @PostMapping("/testjson")
    public Object testjson(@RequestBody Map<String,String> map) {
        System.out.println(map);
        String testData = "{\n" +
                "  \"code\": 200,\n" +
                "  \"msg\": \"success\",\n" +
                "  \"result\": {\n" +
                "    \"date\": \"2023-12-30\",\n" +
                "    \"week\": \"星期六\",\n" +
                "    \"province\": \"河南\",\n" +
                "    \"area\": \"郑州\",\n" +
                "    \"areaid\": \"101180101\",\n" +
                "    \"weather\": \"晴\",\n" +
                "    \"weatherimg\": \"qing.png\",\n" +
                "    \"weathercode\": \"qing\",\n" +
                "    \"real\": \"13.9℃\",\n" +
                "    \"lowest\": \"-2℃\",\n" +
                "    \"highest\": \"14℃\",\n" +
                "    \"wind\": \"西风\",\n" +
                "    \"windspeed\": \"12\",\n" +
                "    \"windsc\": \"3级\",\n" +
                "    \"sunrise\": \"07:32\",\n" +
                "    \"sunset\": \"17:23\",\n" +
                "    \"moonrise\": \"\",\n" +
                "    \"moondown\": \"\",\n" +
                "    \"pcpn\": \"0\",\n" +
                "    \"uv_index\": \"0\",\n" +
                "    \"aqi\": \"124\",\n" +
                "    \"quality\": \"轻度\",\n" +
                "    \"vis\": \"8\",\n" +
                "    \"humidity\": \"25\",\n" +
                "    \"alarmlist\": [],\n" +
                "    \"tips\": \"冬季晴天需注意保湿，外出避免长时间紫外线照射。该地区今日温差较大，建议根据实际情况适时调整衣着安排。天气寒冷，请注意防寒保暖。建议着装：棉衣、羽绒服、冬大衣、皮夹克加羊毛衫、厚呢外套、呢帽、手套等；年老体弱者尽量少外出。空气质量较差，敏感人群建议减少体力消耗类户外活动。\"\n" +
                "  }\n" +
                "}";
        return JSON.parseObject(testData, Weather.class);
    }
    @PostMapping("/testjson1")
    public Object testjson1(@RequestBody Weather weather) {
        System.out.println(weather);
        String testData = "{\n" +
                "  \"code\": 200,\n" +
                "  \"msg\": \"success\",\n" +
                "  \"result\": {\n" +
                "    \"date\": \"2023-12-30\",\n" +
                "    \"week\": \"星期六\",\n" +
                "    \"province\": \"河南\",\n" +
                "    \"area\": \"郑州\",\n" +
                "    \"areaid\": \"101180101\",\n" +
                "    \"weather\": \"晴\",\n" +
                "    \"weatherimg\": \"qing.png\",\n" +
                "    \"weathercode\": \"qing\",\n" +
                "    \"real\": \"13.9℃\",\n" +
                "    \"lowest\": \"-2℃\",\n" +
                "    \"highest\": \"14℃\",\n" +
                "    \"wind\": \"西风\",\n" +
                "    \"windspeed\": \"12\",\n" +
                "    \"windsc\": \"3级\",\n" +
                "    \"sunrise\": \"07:32\",\n" +
                "    \"sunset\": \"17:23\",\n" +
                "    \"moonrise\": \"\",\n" +
                "    \"moondown\": \"\",\n" +
                "    \"pcpn\": \"0\",\n" +
                "    \"uv_index\": \"0\",\n" +
                "    \"aqi\": \"124\",\n" +
                "    \"quality\": \"轻度\",\n" +
                "    \"vis\": \"8\",\n" +
                "    \"humidity\": \"25\",\n" +
                "    \"alarmlist\": [],\n" +
                "    \"tips\": \"冬季晴天需注意保湿，外出避免长时间紫外线照射。该地区今日温差较大，建议根据实际情况适时调整衣着安排。天气寒冷，请注意防寒保暖。建议着装：棉衣、羽绒服、冬大衣、皮夹克加羊毛衫、厚呢外套、呢帽、手套等；年老体弱者尽量少外出。空气质量较差，敏感人群建议减少体力消耗类户外活动。\"\n" +
                "  }\n" +
                "}";
        return JSON.parseObject(testData, Weather.class);
    }
}
